<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use GuzzleHttp\Client;

class TaobaoAuthController extends Controller
{
    // 生成授权URL并重定向
    public function redirectToAuth()
    {
        $params = [
            'response_type' => 'code',
            'client_id'     => env('TAOBAO_APP_KEY'),
            'redirect_uri'  => env('TAOBAO_REDIRECT_URI'),
            'state'         => csrf_token(), // CSRF保护
            'view'          => 'web'        // 网页授权方式
        ];

        $authUrl = 'https://oauth.taobao.com/authorize?' . http_build_query($params);
        
        return redirect()->away($authUrl);
    }

    // 处理淘宝回调
    public function handleCallback(Request $request)
    {
        // 验证state防止CSRF攻击
        if ($request->state !== csrf_token()) {
            abort(419, 'Invalid state parameter');
        }

        // 获取授权码
        $code = $request->code;
        if (!$code) {
            return response()->json(['error' => 'Authorization code missing'], 400);
        }

        // 获取Access Token
        $tokenData = $this->getAccessToken($code);

        // 处理返回结果
        if (isset($tokenData['access_token'])) {
            // 存储session到数据库或会话中
            $accessToken = $tokenData['access_token'];
            $refreshToken = $tokenData['refresh_token'];
            $expiresIn = $tokenData['expires_in'];
            
            // 这里添加您的存储逻辑（数据库、Session等）
            // 例如: session(['taobao_access_token' => $accessToken]);
            
            return response()->json([
                'access_token' => $accessToken,
                'expires_in' => $expiresIn,
                'refresh_token' => $refreshToken
            ]);
        }

        return response()->json(['error' => $tokenData['error_description'] ?? 'Unknown error'], 400);
    }

    // 获取Access Token私有方法
    private function getAccessToken($code)
    {
        $client = new Client([
            'base_uri' => 'https://oauth.taobao.com/',
            'timeout'  => 5.0,
        ]);

        try {
            $response = $client->post('token', [
                'form_params' => [
                    'grant_type'    => 'authorization_code',
                    'client_id'     => env('TAOBAO_APP_KEY'),
                    'client_secret' => env('TAOBAO_APP_SECRET'),
                    'code'          => $code,
                    'redirect_uri'  => env('TAOBAO_REDIRECT_URI')
                ]
            ]);

            return json_decode($response->getBody(), true);
            
        } catch (\Exception $e) {
            return [
                'error' => 'request_failed',
                'error_description' => $e->getMessage()
            ];
        }
    }

    // 刷新Token方法（可选）
    public function refreshToken($refreshToken)
    {
        $response = Http::asForm()->post('https://oauth.taobao.com/token', [
            'grant_type' => 'refresh_token',
            'client_id' => env('TAOBAO_APP_KEY'),
            'client_secret' => env('TAOBAO_APP_SECRET'),
            'refresh_token' => $refreshToken
        ]);

        return $response->json();
    }
}
